package com.example.basic.cls;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class Test1 {

    static Map<Object, Object> map = new HashMap<>();

    public static void main(String[] args) {
        int _1M = 1024 * 1024;

        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        Thread thread = new Thread(() -> {
            try {
                int cnt = 0;
                WeakReference<byte[]> k;
                while ((k = (WeakReference<byte[]>) referenceQueue.remove()) != null){
                    System.out.println((cnt++) + "回收了：" + k);
                }
            } catch (InterruptedException e) {
                //循环结束
            }
        });
        thread.setDaemon(true);
        thread.start();

        Object value = new Object();
//        Map<Object, Object> map = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            byte[] bytes = new byte[_1M];
            WeakReference<byte[]> weakReference = new WeakReference<>(bytes, referenceQueue);
            map.put(weakReference,value);
        }
        System.out.println("map size->" + map.size());
        for (Object o : map.keySet()) {
            if (o instanceof WeakReference) {
                System.out.println(((WeakReference<byte[]>)o).get());
            }

        }

        while (true) {

        }
    }

}
